package com.liseen.loader
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.utils.ByteArray;
	
	public class BinaryItem extends LoadItem
	{
		private var _dataLoader:URLLoader;
		public function BinaryItem(url:String, type:String)
		{
			super(url, type);
		}
		
		override public function onErrorHandler(event:ErrorEvent):void
		{
			super.onErrorHandler(event);
		}
		
		override public function onCompleteHandler(event:Event):void
		{
			this.content = event.target.data;
			if(this.content is ByteArray)
			{
				if(((this.content as ByteArray)[0] == 120)&&((this.content as ByteArray)[1] == 156))
				{
					(this.content as ByteArray).uncompress();
				}
			}
			
			super.onCompleteHandler(event);
		}
		
		override public function load():void
		{
			super.load();
			this._dataLoader = new URLLoader();
			this._dataLoader.dataFormat = URLLoaderDataFormat.BINARY;
			_dataLoader.addEventListener(ProgressEvent.PROGRESS, onProgressHandler, false, 0, true);
			_dataLoader.addEventListener(Event.COMPLETE, onCompleteHandler, false, 0, true);
			_dataLoader.addEventListener(IOErrorEvent.IO_ERROR, onErrorHandler, false, 0, true);
			_dataLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, super.onHttpStatusHandler, false, 0, true);
			_dataLoader.addEventListener(Event.OPEN, onStartedHandler, false, 0, true);
			_dataLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, super.onSecurityErrorHandler, false, 0, true);
			
			try
			{
				_dataLoader.load(urlRequest);
			}
			catch(e:SecurityError)
			{
				onSecurityErrorHandler(e as ErrorEvent);
			}
		}
		
		override protected function cleanListeners():void
		{
			if (_dataLoader)
			{
				_dataLoader.removeEventListener(ProgressEvent.PROGRESS, onProgressHandler, false);
				_dataLoader.removeEventListener(Event.COMPLETE, onCompleteHandler, false);
				_dataLoader.removeEventListener(IOErrorEvent.IO_ERROR, onErrorHandler, false);
				_dataLoader.removeEventListener(Event.OPEN, onStartedHandler, false);
				_dataLoader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, super.onHttpStatusHandler, false);
				_dataLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, super.onSecurityErrorHandler, false);
			}
		}
		
		override public function onStartedHandler(_arg1:Event):void
		{
			super.onStartedHandler(_arg1);
		}
		
		override public function stop():void
		{
			try
			{
				if (_dataLoader)
				{
					_dataLoader.close();
				}
			}
			catch(e:Error)
			{
			}
			super.stop();
		}
		
		override public function destroy():void
		{
			stop();
			cleanListeners();
			content = null;
			_dataLoader = null;
		}
	}
}